#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>

#define BUFFER_SIZE 1024

int main(int argc, char **argv) {
        char ch                         = 0;
        char *buffer                    = NULL;
        char *db                        = NULL;
        FILE *fd                        = NULL;
        unsigned long count             = 0;
        unsigned long line_number       = 0;

        if (argc != 3) {
            fprintf(stderr, "USAGE: getline <file> <line number>\n");
            exit(1);
        }

        if ((fd = fopen(argv[1], "r")) == NULL) {
            perror("Could not open file\n");
            exit(1);
        }
        
        line_number = atoi(argv[2]);
        buffer = (char*)malloc(BUFFER_SIZE);
        db = (char*)malloc(BUFFER_SIZE);

        for (count = 0; (count < line_number); count++) {
            if (ch == 0) {
                fscanf(fd, "%s", buffer);
                if (!strncmp(buffer, "USE", BUFFER_SIZE)) {
                    fscanf(fd, "%s", db);
                }
            }
            while ((ch = getc(fd)) != '\n');
            ch = 0;
        }
        printf("In database: %s\n", db);
        while ((ch = getc(fd)) != '\n') {
            putc(ch, stdout);
        }

        free(buffer);
        free(db);
        fclose(fd);
        return 0;
}

